<?php

/**
 * @version     $Id: AdminsafeIpChecker.php 3 2010-10-08 17:49:35Z obalyuk87@gmail.com $
 * @package     AdminSafe
 * @subpackage  Components
 * @copyright   Copyright (C) 2010 Oleksandr Balyuk (www.boolcast.com)
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL v2
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
// No direct access
defined('_JEXEC') or die('Restricted access');
require_once JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_adminsafe' . DS . 'classes' . DS . 'AdminsafeObject.php';
require_once JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_adminsafe' . DS . 'helpers' . DS . 'AdminsafeUserDetector.php';

/**
 * Description of AdminsafeIpChecker
 *
 * @author Oleksandr Balyuk <obalyuk@boolcast.com>
 */
class AdminsafeIpChecker extends AdminsafeObject {

    /**
     * Default Constructor
     */
    public function __construct() {
        parent::__construct();

        //
        $tablePath = $this->_componentPath . DS . 'tables';
        JTable::addIncludePath($tablePath);
    }

    /**
     * Checks to see if ip is blacklisted, if IP is not specified IP of
     * current user will be used
     *
     * @param string $email
     * @return bool True on success
     */
    public function isBlackListedIpAddress($ip = null) {

        if (!$ip) {
            $ip = AdminsafeUserDetector::getIpAddress();
        }

        //
        return $this->_isBlackListed($ip);
    }

    /**
     * Checks to see if ip is whitelisted, if IP is not specified IP of
     * current user will be used
     *
     * @param string $ip
     * @return bool
     */
    public function isWhiteListedIpAddress($ip = null) {
        if (!$ip) {
            $ip = AdminsafeUserDetector::getIpAddress();
        }

        return $this->_isWhiteListed($ip);
    }

    /**
     * Flags the IP address "autoban increments", if the count of warning exceeds 
     * the maximum allowed warnings, BAN the IP and remove it from "flag" table
     * 
     * if IP is not specified IP of current user will be used
     *
     * @param string $ip
     * @return bool
     */
    public function flagIpAddress($ip = null) {
        if (!$ip) {
            $ip = AdminsafeUserDetector::getIpAddress();
        }

        //
        $autoBan = JTable::getInstance('autoban', 'Table');
        /* @var $autoBan TableAutoban */
        $source = array('ip_address' => $ip);

        //  If IP is not in the warning table
        if (!$autoBan->load($ip)) {
            $autoBan->save($source);
        }

        //
        $params = JComponentHelper::getParams('com_adminsafe');
        $maxAllowed = (int) $params->get('autoBanAttemptLimit', 0);


        if ($autoBan->hits + 1 >= $maxAllowed) {

            //  Add new IP BAN record
            $blackList = JTable::getInstance('ipblacklist', 'Table');
            //  If IP Successfully banned
            $source['type'] = 1;
            if ($blackList->save($source)) {
                //  Delete Autoban tracker Record
                $autoBan->delete();
            }
        } else {
            //
            $autoBan->hit($oid);
        }
    }

    /**
     * Deletes Autoban record for given IP
     *
     *  if IP is not specified IP of current user will be used
     * 
     * @param string $ip
     * @return bool
     */
    public function deleteAutoBan($ip=null) {
        if (!$ip) {
            $ip = AdminsafeUserDetector::getIpAddress();
        }
        
        //
        $autoBan = JTable::getInstance('autoban', 'Table');
        /* @var $autoBan TableAutoban */

        return $autoBan->delete($ip);
    }

    /**
     * Checks to see if specified IP Address is black listed
     *
     * @param string $ip
     * @return bool True if IP address is black listed
     */
    protected function _isBlackListed($ip) {

        if ($ip) {
            $tbl = JTable::getInstance('ipblacklist', 'Table');
            return (bool) $tbl->load($ip);
        }

        //
        return true;
    }

    /**
     * Checks to see if passed IP address is white listed
     *
     * @param string $ip
     * @return bool True if IP is whitelisted
     */
    protected function _isWhiteListed($ip) {
        //
        $params = JComponentHelper::getParams('com_adminsafe');
        $whiteListedIps = $params->get('autoBanExcludeIps', '');
        $whiteListedIps = explode(',', $whiteListedIps);

        if ($whiteListedIps) {
            //  Scan through all IPs
            foreach ($whiteListedIps as $whiteIp) {
                //  Clean IP, might have white spaces
                $whiteIp = trim($whiteIp);

                //  Check for match
                if ($ip == $whiteIp) {
                    return true;
                }
            }
        }

        return false;
    }

}